'use strict';

import React from 'react';

import {HttpService, Toast} from '../utils'
// import {HttpService, Toast}  from'../Http';

import phone from '../img/login/phone.png'
import pwd from '../img/login/pwd.png'
import user from '../img/login/user.png'

import Model from './common/model'

import header from '../img/login/header.jpg'
import footer from '../img/login/footer.jpg'

import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';

//import {Router, Route, IndexRoute, browserHistory} from 'react-router';

import Link from './common/Link'
//import WxServer from '../wx/WxServer'

import {doLogin2} from '../action/index'

class Login extends React.Component {
    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    constructor(props) {
        super(props);
        this.state = {
            model: {},
            banners: {},
            flag: false,
            wxlogincbFlag: false,
            openid: '',
            wxgo: true
        };
        this.modelConfig = {
            header: <div className="header">

                <img src={header} className="app-all-img"/>

            </div>,
            content: <div className="content">
                <div className="_header">
                    市民认证
                </div>
                <div className="_content">
                    姓名和身份证不匹配，身份证姓名和身份证不匹配，身份证姓名和身份证不匹配，身份证姓名和身份证不匹配，身份证
                </div>
                <div className="_footer">
                    去认证
                </div>
            </div>,
            footer: <div className="footer">
                    <img src={footer} className="app-all-img"/>
                </div>

        }
    }

    componentWillMount() {
        this.setState({openid: localStorage.openid});
        const appdown = localStorage.appdown;
        localStorage.clear();
        localStorage.appdown = appdown;
        let state = this.name('state');
        if (state == 'teacher') {
            document.title = '随寻通（教师端）';
            localStorage.teacher = 1;
        } else {
            state = 'suixun';
        }
        // if (/micromessenger/.test(navigator.userAgent.toLowerCase())) {
        //     if (this.name('code')) {
        //         this.a();
        //         this.setState({wxgo: false})
        //     } else {
        //         location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?' +
        //             'appid=wx85577a457cfcd222&redirect_uri=https%3A%2F%2Fwx.17find.com%2F&response_type=code&scope=snsapi_userinfo&state=' + state + '#wechat_redirect'
        //     }
        // } else {
        //     this.setState({wxgo: false})
        // }
        this.setState({wxgo: false})
    }
    // componentDidMount() {
    //     this.refs.phone.value = 13868113229
    //     this.refs.pwd.value = 12345678
    // }

    componentWillUnmount() {
        let loginStr = '登录'
        if (localStorage.teacher == 1)
            loginStr = '登录-教师端'
        _hmt.push(['_trackEvent', 'page', 'login', loginStr]);
        console.log(loginStr);
    }

    a() {
        if (!this.props.params.type) {
            setTimeout(() => {
                if (localStorage.teacher != 1){}
                    //WxServer.init()
            }, 0);
            setTimeout(async() => {
                let sondData = {
                    code: this.name('code')
                };
                if (localStorage.teacher == 1)
                    sondData.state = 'teather';
                const result = await HttpService.query({url: '/thirdparty/weixin/wxlogin_callback', data: sondData});
                this.setState({openid: result.data.openid});
                localStorage.openid = result.data.openid;
                if (result.code == 50006) { //未绑定微信需要跳到登录页并传openid
                    return;
                } else if (result.code == 10008) { //返回token直接跳转首页
                    if (localStorage.teacher == 1) {
                        if (result.data.yijiaoyun) {
                            location.href = result.data.yijiaoyun;
                        } else {
                            const teacherData = await HttpService.query({
                                url: '/teacherapp/system/getThirdParty',
                                data: {
                                    token: result.data.token
                                }
                            });
                            if (teacherData.code == 10134) {
                                location.href = teacherData.data.yijiaoyun;
                                return;
                            }
                            Toast.toast(teacherData.msg)
                        }
                        return;
                    }

                    this.props.doLogin2(result.data.token, result.data.userid, this);
                    this.context.router.push('/map/' + result.data.token + '/' + result.data.userid);
                    localStorage.token = result.data.token;
                    localStorage.userid = result.data.userid;
                    return;
                } else if (result.code == 100072) { //如果账号不存在跳转到注册页并传openid
                    this.context.router.push('/register');
                    return;
                } else if (result.code == 100073) { //未扫描设备，跳到添加设备页
                    localStorage.userid = result.data.userid;
                    this.context.router.push('/AddDevice/true');
                    return;
                }
                Toast.toast(result.msg)
            }, 1);
        }
    }

    name(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = location.search.substr(1).match(reg);
        if (r != null)
            return unescape(r[2]);
        return null;
    }

    async login() {
        const phone = this.refs.phone.value;
        const pwd = this.refs.pwd.value;
        if (phone == '') {
            Toast.toast('请输入手机号');
            return;
        } else if (!/^1[34578]\d{9}$/.test(phone)) {
            Toast.toast('手机格式不正确');
            return;
        }
        if (!pwd) {
            Toast.toast('请输入密码');
            return;
        }
        localStorage.delDevice = 0;
        localStorage.userphone = phone;

        let loginUrl = '/app/user/login'
        if (localStorage.teacher == 1)
            loginUrl = '/teacherapp/teacher/login'
        var result = await HttpService.query({
            url: loginUrl,
            data: {
                account: phone,
                password: pwd,
                weixinclient: 'true',
                openid: this.state.openid
            }
        });
        if (result.code == 10008) {
            this.props.doLogin2(result.data.token, result.data.userid, this);
            this.context.router.push('/map/' + result.data.token + '/' + result.data.userid);
            localStorage.token = result.data.token;
            localStorage.userid = result.data.userid;
            return;
        } else if (result.code == 100073) {
            localStorage.userid = result.data.userid;
            this.context.router.push('/AddDevice/true');
            return;

        } else if (result.code == 20002) { //教师端
            if (result.data.yijiaoyun) {
                location.href = result.data.yijiaoyun;
            } else {
                const teacherData = await HttpService.query({
                    url: '/teacherapp/system/getThirdParty',
                    data: {
                        token: result.data.token
                    }
                });
                if (teacherData.code == 10134) {
                    location.href = teacherData.data.yijiaoyun;
                    return;
                }
                Toast.toast(teacherData.msg)
            }
            return;
        }
        Toast.toast(result.msg)
    }

    render() {
        const {model, flag, wxgo} = this.state;
        return (
            <div>
                {wxgo == true
                    ? <div className='loadwx'></div>
                    : <div>
                        {flag == false
                            ? <div className="app-login app-padding-lr24" ref='_login'>

                                    <Model modelConfig={this.modelConfig} flag={model.flag}/>
                                    <div className="step">
                                        <div className="s-center">
                                            <div className="login-img">
                                                <img src={user} className="app-wh100-all"/>

                                            </div>
                                        </div>
                                    </div>

                                    <div className="step border-bottom app-wh120">
                                        <div className="app-wh-45 app-margin-right24">
                                            <img className="app-wh100-all-radius" src={phone}/>
                                        </div>

                                        <div className="s-flex1 app-666-font30">
                                            <input className="app-333-font28 login-input" placeholder='手机号' type="tel" ref='phone'/>
                                        </div>

                                    </div>
                                    <div className="step border-bottom app-wh120">
                                        <div className="app-wh-45 app-margin-right24">
                                            <img className="app-wh100-all-radius" src={pwd}/>
                                        </div>

                                        <div className="s-flex1 app-666-font30">
                                            <input className="app-333-font28 login-input" placeholder="6-20位字符密码，区分大小写" type="password" ref="pwd"/>
                                        </div>

                                    </div>

                                    <div className="step app-yellow-radius-check-button login-btn" onClick={this.login.bind(this)}>
                                        <div className="s-center">登录</div>
                                    </div>

                                    <div className="step">
                                        <Link to={'/register'} className="s-flex1 app-a">
                                            <div className="s-flex1 s-j-end app-333-font28">新用户开通</div>
                                        </Link>
                                        <div className="app-padding-lr50 app-with1"></div>
                                        <Link to={'/ForgetPwd'} className="s-flex1 app-a">
                                            <div className="s-flex1 app-333-font28">忘记密码</div>
                                        </Link>
                                    </div>
                                </div>
                            : ''
}
                    </div>}
            </div>
        )
    }
}

const mapStateToProps = state => {
    return {};
};
const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({

        doLogin2: doLogin2
    }, dispatch);
};
export default connect(mapStateToProps, mapDispatchToProps)(Login);
